#pragma once
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <string>
#include <functional>
#include "Log.hpp"

static const int gsockfd = -1;
static const uint16_t glocalport = 8888;
enum{
    SOCKET_ERROR = 1,
    BIND_ERROR
};

using func_t = std::function<std::string(const std::string)>;

class UdpServer
{
public:
    UdpServer(func_t func, uint16_t localport=glocalport)
    :_sockfd(gsockfd)
    ,_localport(localport)
    ,_isRunning(false)
    ,_func(func)
    {}
    UdpServer(const UdpServer&) = delete;
    const UdpServer& operator=(const UdpServer&) = delete;
    void InitServer()
    {
        //1. 创建socket文件
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            LOG(FATAL, "socket error\n");
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG, "socket creat success _sockfd: %d\n", _sockfd);

        //2. 将本地的ip地址、该程序的端口号和创建好的socket文件关联起来
        struct sockaddr_in local; 
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET; 
        local.sin_port = htons(_localport);
        local.sin_addr.s_addr = INADDR_ANY;
        //bind
        int n = bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
        if(n < 0)
        {
            //绑定失败直接退出程序没必要继续执行
            LOG(FATAL, "bind error\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "bind creat success\n");
    }
    //服务器上跑的程序是一直运行的，
    void Start()
    {
        //启动程序
        _isRunning = true;
        char in_buffer[1024];
        while(_isRunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, in_buffer, sizeof(in_buffer)-1, 0, (struct sockaddr*)&peer, &len);
            if(n > 0)
            {
                //回调函数
                in_buffer[n] = 0;
                std::string result = _func(in_buffer);
                sendto(_sockfd, result.c_str(), sizeof(result), 0, (struct sockaddr*)&peer, len);
            }
        }
    }
    ~UdpServer()
    {
        if(_sockfd > gsockfd) close(_sockfd);
    }
private:
    int _sockfd;
    uint16_t _localport;
    bool _isRunning;
    func_t _func;
};